import {useNavigate} from "react-router-dom";
import {useEffect, useState} from "react";
import styles from './styles.module.css'
import {useDispatch, useSelector} from "react-redux";
import {AppDispatch, RootState} from "../../store/inedx.ts";
import {logout} from "../../store/slices/auth-slice.ts";
import logo from '../../assets/react.svg'
import {EditOutlined, FileAddOutlined, LogoutOutlined} from '@ant-design/icons';
import {Button, Checkbox, Form, type FormProps, Input, message, Modal} from "antd";
import {namespaceDelete, namespaceList, namespaceSave, NamespaceSelectEntity, namespaceUpdate} from "../../apis";
import {updateNameSpace} from "../../store/slices/app-slice.ts";

class NamespaceSelectEntityImpl implements NamespaceSelectEntity {
    createdAt: string = '';
    label: string = '';
    name: string = '';
    status: boolean = false;
    uid: string = '';
    updatedAt: string = '';
}

/**
 * 主页页面
 */
function Home() {
    const navigate = useNavigate();
    const dispatch = useDispatch<AppDispatch>();
    const {username, token} = useSelector((state: RootState) => state.auth);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [isModalEdit, setIsModalEdit] = useState(false);
    const [form] = Form.useForm();
    const [namespaces, setNamespaces] = useState<NamespaceSelectEntity[]>([]);
    const [editNamespace, setEditNamespace] = useState<NamespaceSelectEntity>(new NamespaceSelectEntityImpl());

    const getComponentsData = async () => {
        const resp = await namespaceList();
        if (resp.code === 0) {
            setNamespaces(resp.data || []);
        } else {
            message.warning(resp.message || '读取数据失败')
        }
    }

    const onConfirmExit = () => {
        dispatch(logout());
        navigate('/login');
    }

    const onDelete = async () => {
        const resp = await namespaceDelete(editNamespace);
        message.info(resp.message).then();
        if (resp.code === 0) {
            getComponentsData().then();
            setIsModalEdit(false);
        }
    }

    const onFinish: FormProps<NamespaceSelectEntity>['onFinish'] = async (values) => {
        const ns = {...editNamespace, ...values};
        let resp = null;
        if (ns.uid) {
            resp = await namespaceUpdate(ns);
        } else {
            resp = await namespaceSave(ns);
        }
        message.info(resp.message).then();
        if (resp.code === 0) {
            getComponentsData().then();
            setIsModalEdit(false);
        }
    };

    useEffect(() => {
        getComponentsData().then();
    }, [username, token])  // 空依赖数组表示仅执行一次

    return (<>
        <div className={styles.root}>
            <div className={styles.header}>
                <div className={styles.headerLogo}>
                    <div>
                        <img src={logo} alt={'logo'} style={{
                            width: '60px',
                            height: '60px',
                            marginRight: '10px'
                        }}/>
                    </div>
                    <div>
                        <b style={{fontSize: '20px'}}>命名空间列表</b>
                        <br/>
                        <span
                            style={{fontSize: '12px'}}>通过命名空间划分数据区，如每个公司主体可以建一个空间</span>
                    </div>
                </div>
                <div onClick={() => setIsModalOpen(true)} style={{cursor: 'pointer'}}>
                    <span style={{fontSize: '18px', textTransform: 'capitalize'}}>{username}</span>
                    <LogoutOutlined style={{marginLeft: '5px'}}/>
                </div>
            </div>

            <div className={styles.body}>
                <div className={styles.container}>
                    {namespaces.map((item) => (
                        <div className={styles.containerItem} key={item.uid}>
                            <p style={{textAlign: 'center'}} onClick={() => {
                                dispatch(updateNameSpace({
                                    nameSpaceId: item.uid,
                                    nameSpaceName: item.name,
                                    nameSpaceLabel: item.label,
                                }));
                                navigate('/home');
                            }}>
                                <b>{item.name}</b>
                                <br/>
                                <span>{item.label}</span>
                                <br/>
                                <span>{item.status ? 'yes' : 'no'}</span>
                            </p>

                            <div className={styles.containerItemClose} onClick={() => {
                                setEditNamespace(JSON.parse(JSON.stringify(item)));
                                form.setFieldsValue(JSON.parse(JSON.stringify(item)))
                                setIsModalEdit(true);
                            }}>
                                <EditOutlined style={{fontSize: '25px'}}/>
                            </div>
                        </div>
                    ))}
                    <div className={styles.containerItem} onClick={() => {
                        setEditNamespace(new NamespaceSelectEntityImpl());
                        form.setFieldsValue(new NamespaceSelectEntityImpl())
                        setIsModalEdit(true);
                    }}>
                        <FileAddOutlined style={{fontSize: '30px'}}/>
                    </div>
                </div>

                <div style={{width: '100%', height: '100px'}}>&nbsp;</div>
            </div>

            <Modal
                title="系统提示"
                open={isModalOpen}
                centered={true}
                onOk={onConfirmExit}
                onCancel={() => setIsModalOpen(false)}
                okText={'确定'}
                cancelText={'取消'}>
                <p>确定退出登录吗？</p>
            </Modal>

            <Modal
                title={editNamespace?.name ? '命名空间信息' : '新增命名空间'}
                open={isModalEdit}
                centered={true}
                footer={null}
                onCancel={() => setIsModalEdit(false)}>

                <Form
                    name="basic"
                    form={form}
                    labelCol={{span: 5}}
                    wrapperCol={{span: 16}}
                    style={{maxWidth: 500, marginTop: '35px'}}
                    autoComplete="off"
                    preserve={false}
                    onFinish={onFinish}>
                    <Form.Item<NamespaceSelectEntity>
                        label="名称" name="name" initialValue={editNamespace?.name || ''}
                        rules={[{required: true, message: '命名空间名称不能为空'}]}>
                        <Input/>
                    </Form.Item>

                    <Form.Item<NamespaceSelectEntity>
                        label="标签" name="label" initialValue={editNamespace?.label || ''}>
                        <Input/>
                    </Form.Item>

                    <Form.Item<NamespaceSelectEntity>
                        label="启用" name="status" initialValue={editNamespace?.status || false}
                        // initialValue={(editNamespace?.status || 0) > 0 || false}
                        // getValueProps={value => ({checked: value > 0})}
                        // getValueFromEvent={e => e.target.checked === true ? 1 : 0}
                        valuePropName="checked">
                        <Checkbox>使命名空间生效</Checkbox>
                    </Form.Item>

                    <Form.Item label={null}>
                        <Button type="primary" htmlType="submit">
                            提交
                        </Button>
                        <span>&nbsp;&nbsp;</span>
                        {editNamespace?.name && <Button htmlType="button" onClick={onDelete}>删除</Button>}
                    </Form.Item>
                </Form>

            </Modal>
        </div>
    </>);
}

export default Home;